package com.kvn.backdoor.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

/**
 * 操作xml文件，当作 DB 来使用
 * Created by wangzhiyuan on 2018/8/16
 */
public class XmlDbManager extends XmlManager {
    protected final Log logger = LogFactory.getLog(getClass());

    private TableEnum table;

    public XmlDbManager use(TableEnum table){
        this.table = table;
        return this;
    }


    public int insert(Object entity){
        this.saveContent(entity);
        return 1;
    }

    public <T> T selectOne(T entity){
        BeanWrapper beanWrapper = new BeanWrapperImpl(entity);
        PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
        List<Condition> conditionList = new ArrayList<>();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propName = propertyDescriptor.getName();
            if (!"class".equals(propName) && beanWrapper.getPropertyValue(propName) != null) {
                Condition condition = new Condition();
                condition.setKey(propName);
                condition.setValue(beanWrapper.getPropertyValue(propName).toString());
                conditionList.add(condition);
            }
        }

        List<?> resultList = selectList(entity.getClass(), conditionList.toArray(new Condition[]{}));
        if (resultList != null && resultList.size() != 1) {
            logger.warn("检索出的条数大于1，" + JSON.toJSONString(resultList));
        }
        return (T) resultList.get(0);
    }

    public <T> List<T> selectList(Class<T> dataType, Condition... conditions){
        List<String> allData = getAllRawData();
        List<T> filteredList = new ArrayList<>();
        allData.forEach(data -> {
            JSONObject jsonObject = JSONObject.parseObject(data);
            if (matches(jsonObject, conditions)) {
                T obj = JSONObject.parseObject(data, dataType);
                filteredList.add(obj);
            }
        });
        return filteredList;
    }

    private boolean matches(JSONObject jsonObject, Condition[] conditions) {
        if (conditions == null || conditions.length <= 0) {
            return true;
        }

        for (Condition condition : conditions) {
            Object value = jsonObject.get(condition.getKey());
            if (value != null && value.toString().equals(condition.getValue())) {
                return true;
            }
        }

        return false;
    }

    @Override
    protected String getFile() {
        return table.getTableName();
    }
}
